<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:excelmerge:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['project:excelmerge:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['project:excelmerge:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['project:excelmerge:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="excelmergeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" v-if="false"/>
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="附件(去年)" align="center" prop="fjidone" />
      <el-table-column label="附件(今年)" align="center" prop="fjidtwo" />
      <el-table-column label="创建用户名称" align="center" prop="createusername" />
      <el-table-column label="创建部门名称" align="center" prop="createdeptname" />
      <el-table-column label="创建时间" align="center" prop="createtime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createtime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:excelmerge:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:excelmerge:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改excel合并对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body @close="closeDialog">
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件(去年)" prop="fjidone">
              <el-upload
                class="upload-demo"
                action="/dev-api/project/fujian/file/upload/1"
                :on-success="handleSuccess"
                :on-error="handleError"
                :before-remove="handleRemove"
                :headers="uploadHeaders"
                :data="uploadParam"
                multiple
                :limit="1"
                :file-list="fjidoneList"
                drag
                :on-exceed="handleExceed"
                >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或点击上传</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件(今年)" prop="fjidtwo">
              <el-upload
                class="upload-demo"
                action="/dev-api/project/fujian/file/upload/2"
                :on-success="handleSuccess"
                :on-error="handleError"
                :before-remove="handleRemove"
                :headers="uploadHeaders"
                :data="uploadParam"
                multiple
                :file-list="fjidtwoList"
                drag
                :on-exceed="handleExceed"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或点击上传</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" style="text-align: center">
        <el-button :loading="buttonLoading" plain type="primary" @click="submitForm">保存</el-button>
        <el-button @click="closeDialog" plain>取消</el-button>
        <el-button type="primary" plain @click="handleExcel">生成 Excel</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listExcelmerge, getExcelmerge, genExcel, delExcelmerge, addExcelmerge, updateExcelmerge } from "@/api/project/excelmerge";
import { delFujian, getFujian } from "@/api/project/fujian";
import { getToken } from '@/utils/auth'

export default {
  name: "Excelmerge",
  data() {
    return {
      fjidoneList: [],
      fjidtwoList: [],
      uploadHeaders: { 'Authorization': 'Bearer ' + getToken() }, // 如果需要CSRF保护的话
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // excel合并表格数据
      excelmergeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        fjidone: undefined,
        fjidtwo: undefined,
        fjidthree: undefined,
        fjidfour: undefined,
        createuserid: undefined,
        createusername: undefined,
        createdeptid: undefined,
        createdeptname: undefined,
        createtime: undefined
      },
      uploadParam: {
        type: '1'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ]
      },
      fjidonefileList: [],
      fjidtwofileList: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 生成Excel
    handleExcel() {
      // 1.先判断当前的 去年附件，以及今年附件是否已经上传
      let one = this.form.fjidone
      let two = this.form.fjidtwo
      if (one === '' || one === null || one === undefined) {
        this.$message.error("附件(去年) 未上传，请先上传附件")
        return
      }
      if (two === '' || two === null || two === undefined) {
        this.$message.error("附件(今年) 未上传，请先上传附件")
        return
      }
      // 2.生成之前先保存 excel
      if (this.form.id !== undefined) {
        updateExcelmerge(this.form).then(response => {
          this.form = response.data
          console.log("返回数据1---->", response)
          // 3.调用接口处理Excel
          this.getExcel(response.data)
        })
      } else {
        addExcelmerge(this.form).then(response => {
          this.form = response.data
          console.log("返回数据2---->", response.data)
          // 3.调用接口处理Excel
          this.getExcel(response.data)
        })
      }
    },
    getExcel(item) {
      console.log("item", item)
      genExcel(item.id).then(res => {
        console.log("生成完成!", res)
      })
    },
    closeDialog() {
      this.form = {}
      this.fjidoneList = []
      this.fjidtwoList = []
      this.open = false
    },
    handleSuccess(response, file) {
      // 更新状态或者通知用户上传成功
      this.$message.success('上传成功');
      // 上传成功以后，将id设置
      if (response.type === '1') {
        this.fjidoneList.push(response)
        this.form.fjidone = response.fjid
      }else if (response.type === '2') {
        this.fjidtwoList.push(response)
        this.form.fjidtwo = response.fjid
      }
    },
    // 删除回调
    handleRemove(file, fileList) {
      // 调用删除附件功能，将附件进行删除
      let fjId = []
      fjId.push(file.fjid)
      delFujian(fjId).then(res => {
        if (res.code === 200) {
          this.$message.success("删除成功！")
        }
      })
      if (file.type === '1') {
        this.$set(this.form, "fjidone", "")
        this.form.fjidone = ''
      }else if (file.type === '2') {
        this.$set(this.form, "fjidtwo", "")
        this.form.fjidtwo = ''
      }
    },
    // 上传失败回调
    handleError(err, file) {
      // 处理错误并通知用户
      this.$message.error('上传失败：', err);
      this.fjidoneList = []
      this.fjidtwoList = []
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件`);
    },
    /** 查询excel合并列表 */
    getList() {
      this.loading = true;
      listExcelmerge(this.queryParams).then(response => {
        this.excelmergeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        title: undefined,
        fjidone: undefined,
        fjidtwo: undefined,
        fjidthree: undefined,
        fjidfour: undefined,
        createuserid: undefined,
        createusername: undefined,
        createdeptid: undefined,
        createdeptname: undefined,
        createtime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加excel合并";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getExcelmerge(id).then(response => {
        this.form = response.data;
        // 初始化附件列表
        let fjidone = this.form.fjidone
        let fjidtwo = this.form.fjidtwo
        if (fjidone !== '' && fjidone !== null && fjidone !== undefined) {
          getFujian(fjidone).then(res => {
            if (res.code === 200) {
              let obj = res.data
              obj.name = res.data.fjname
              obj.type = '1'
              this.fjidoneList.push(obj)
            }
          })
        }
        if (fjidtwo !== '' && fjidtwo !== null && fjidtwo !== undefined) {
          getFujian(fjidtwo).then(res => {
            if (res.code === 200) {
              let obj = res.data
              obj.name = res.data.fjname
              obj.type = '2'
              this.fjidtwoList.push(obj)
            }
          })
        }
        this.loading = false;
        this.title = "修改excel合并";
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id !== undefined) {
            updateExcelmerge(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addExcelmerge(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除excel合并编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delExcelmerge(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('project/excelmerge/export', {
        ...this.queryParams
      }, `excelmerge_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
